package com.managertrade.util;

import com.esotericsoftware.kryo.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.managertrade.util.strategy.client.BackpackTradingBot;
import lombok.Data;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.net.ssl.*;
import java.math.BigDecimal;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class BackpackApiClientRequest {

    private static final String API_BASE = "https://api.backpack.exchange/api/v1";
    private static OkHttpClient client;
    private boolean useProxy;

    /** ← 新增：动态传入 API KEY */
    private  String apiKey;

    /** ← 新增：动态传入 Base64 私钥 */
    private  String secretKey;
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    /** 订单信息 */
    private OrderInfo order;

    private static volatile BackpackApiClientRequest INSTANCE;

    /** 自动选择代理 + 单例模式 */



    /**
     * 支持动态传入 API KEY & SECRET
     * 其他逻辑完全不动
     */
    public static BackpackApiClientRequest getInstance(String apiKey, String secretKey) {
        if (INSTANCE == null) {
            synchronized (BackpackApiClientRequest.class) {
                if (INSTANCE == null) {

                    boolean enableProxy = autoDetectProxy();

                    INSTANCE = new BackpackApiClientRequest(enableProxy);

                    // ⭐ 动态注入用户传入的 key/secret（仅首次有效）
                    INSTANCE.setApiKey(apiKey);
                    INSTANCE.setSecretKey(secretKey);
                }
            }
        } else {
            // ⭐ 如果实例已存在，可以随时更新 key/secret
            INSTANCE.setApiKey(apiKey);
            INSTANCE.setSecretKey(secretKey);
        }

        return INSTANCE;
    }
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }


    /** 自动识别是否应启用代理 */
    private static boolean autoDetectProxy() {
        try {

            // ① 获取本机 IP
            String localIp = InetAddress.getLocalHost().getHostAddress();

            // ② 自定义判定条件（你可以自己换规则）
            if (localIp.startsWith("192.168.") || localIp.startsWith("10.")) {
                return true; // 在局域网环境 → 使用代理
            }

            // ③ Ping 一下代理，看是否可用
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress("127.0.0.1", 22307), 200);
                return true; // 代理端口可用
            } catch (Exception ignore) {}

        } catch (Exception ignore) {}

        return false;
    }

    /**
     * 内部类：订单信息
     */
    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class OrderInfo {

        /** 订单ID */
        private String id;

        /** 订单创建时间 */
        private String createdAt;

        /** 已成交数量 */
        private String executedQuantity;

        /** 已成交金额 */
        private String executedQuoteQuantity;

        /** 订单失效原因，例如账户被交易暂停 */
        private String expiryReason;

        /** 订单类型，例如 Market、Limit */
        private String orderType;

        /** 是否仅Post订单 */
        private Boolean postOnly;

        /** 订单价格 */
        private String price;

        /** 订单数量 */
        private String quantity;

        /** 订单金额（挂单时） */
        private String quoteQuantity;

        /** 自成交预防类型，例如 RejectTaker */
        private String selfTradePrevention;

        /** 订单状态，例如 Cancelled、Filled、New */
        private String status;

        /** 订单方向，例如 Bid（买）、Ask（卖） */
        private String side;

        /** 止损触发价格 */
        private String stopLossTriggerPrice;

        /** 止损限价 */
        private String stopLossLimitPrice;

        /** 止损触发方式 */
        private String stopLossTriggerBy;

        /** 交易标的，例如 BTCUSDT */
        private String symbol;

        /** 止盈触发价格 */
        private String takeProfitTriggerPrice;

        /** 止盈限价 */
        private String takeProfitLimitPrice;

        /** 止盈触发方式 */
        private String takeProfitTriggerBy;

        /** 有效时间策略，例如 GTC（Good Till Cancel） */
        private String timeInForce;

        /** 触发方式，例如按价格触发 */
        private String triggerBy;

        /** 触发价格 */
        private String triggerPrice;

        /** 触发数量 */
        private String triggerQuantity;

        /** 客户端ID，可用于关联本地订单 */
        private Integer clientId;

        /** 系统订单类型，例如 CollateralConversion */
        private String systemOrderType;

        /** 策略ID，可用于关联策略订单 */
        private String strategyId;

        /** 滑点容忍值 */
        private String slippageTolerance;

        /** 滑点容忍类型，例如 TickSize */
        private String slippageToleranceType;
    }

    /**
     * 构造函数
     * @param useProxy 是否使用代理
     */
    /** 构造函数（新增 apiKey, privateKeyBase64） */
    public BackpackApiClientRequest(boolean useProxy, String apiKey, String secretKey) {
        this.useProxy = useProxy;
        this.apiKey = apiKey;
        this.secretKey = secretKey;
        client = createTLSClient(useProxy);
    }

    public BackpackApiClientRequest(boolean useProxy) {
        this.useProxy = useProxy;
        client = createTLSClient(useProxy);
    }


    public String get(String path, Map<String, String> queryParams) throws Exception {
        return executeWithRetry(() ->{
            HttpUrl.Builder urlBuilder = HttpUrl.parse(API_BASE + path).newBuilder();
            if (queryParams != null) {
                queryParams.forEach(urlBuilder::addQueryParameter);
            }
            HttpUrl url = urlBuilder.build();

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new RuntimeException("HTTP GET failed: " + response.code() + " -> " + response.body().string());
                }
                return response.body().string();
            }
        });

    }

    /**
     * POST 请求
     * @param  ，例如 /orders
     * @param
     * @return 响应字符串
     * @throws Exception
     */
    public String post(List<Map<String, Object>> orderPayload) throws Exception {
        return executeWithRetry(() ->{
            long ts = System.currentTimeMillis();
            String window = "5000";
            String instruction = "orderExecute";

            // 1️⃣ 构建签名字符串
            StringBuilder signingStrBuilder = new StringBuilder();
            for (int i = 0; i < orderPayload.size(); i++) {
                Map<String, Object> order = orderPayload.get(i);

                // 按 key 字母排序
                List<String> keys = new ArrayList<>(order.keySet());
                Collections.sort(keys);

                StringBuilder orderStr = new StringBuilder();
                for (String key : keys) {
                    if (orderStr.length() > 0) {
                        orderStr.append("&");
                    }
                    orderStr.append(key).append("=").append(order.get(key).toString());
                }

                // 每个订单前加 instruction
                if (signingStrBuilder.length() > 0) {
                    signingStrBuilder.append("&");
                }
                signingStrBuilder.append("instruction=").append(instruction).append("&").append(orderStr);
            }

            // 拼 timestamp 和 window
            signingStrBuilder.append("&timestamp=").append(ts).append("&window=").append(window);

            String signingStr = signingStrBuilder.toString();
            String signature = sign(signingStr, INSTANCE.secretKey);
            // 3️⃣ 构建 JSON 请求体
            ObjectMapper mapper = new ObjectMapper();
            String jsonBody = mapper.writeValueAsString(orderPayload);

            RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));
            Request request = new Request.Builder()
                    .url(API_BASE + "/orders")
                    .post(body)
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("X-API-KEY", INSTANCE.apiKey)
                    .addHeader("X-SIGNATURE", signature)
                    .addHeader("X-TIMESTAMP", String.valueOf(ts))
                    .addHeader("X-WINDOW", window)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                int code = response.code();
                String respBody = response.body() != null ? response.body().string() : "<empty body>";

                if (!response.isSuccessful()) {
                    throw new RuntimeException("HTTP POST failed: " + code + " -> " + respBody);
                }
                return respBody;
            }
        });

    }
    // ====== 用于忽略 JSON 中未知字段 ======
    @JsonIgnoreProperties(ignoreUnknown = true)
    private static abstract class IgnoreUnknown {}

    public static    String  orderHistoryQueryAll() throws Exception {
        return executeWithRetry(() ->{
            long ts = System.currentTimeMillis();
            String window = "5000";
            String instruction = "orderHistoryQueryAll";

            // 1️⃣ 构建签名字符串（注意签名规则与 POST 相同）
            StringBuilder signingStrBuilder = new StringBuilder();
            signingStrBuilder.append("instruction=").append(instruction);
            signingStrBuilder.append("&limit=").append(200);
            signingStrBuilder.append("&timestamp=").append(ts);
            signingStrBuilder.append("&window=").append(window);
            String signingStr = signingStrBuilder.toString();
            String signature = sign(signingStr, INSTANCE.secretKey);
            // 3️⃣ 构建 GET 请求 URL
            String url = "https://api.backpack.exchange/wapi/v1/history/orders"+"?limit=" + URLEncoder.encode("200", "UTF-8");

            /*String url = API_BASE + "/orders?marketType=" + URLEncoder.encode(marketType, "UTF-8")
                    + "&symbol=" + URLEncoder.encode(symbol, "UTF-8");*/

            // 4️⃣ 构建请求头
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("X-API-KEY", INSTANCE.apiKey)
                    .addHeader("X-SIGNATURE", signature)
                    .addHeader("X-TIMESTAMP", String.valueOf(ts))
                    .addHeader("X-WINDOW", window)
                    .build();

            // 5️⃣ 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                int code = response.code();
                String respBody = response.body() != null ? response.body().string() : "<empty body>";

                if (!response.isSuccessful()) {
                    throw new RuntimeException("GET Open Orders failed: " + code + " -> " + respBody);
                }

                return respBody;
            }
        });


    }
    // ====== 获取所有未完成订单 ======
    public String getOpenOrders(String marketType, String symbol) throws Exception {
        return executeWithRetry(() ->{
            long ts = System.currentTimeMillis();
            String window = "5000";
            String instruction = "orderQueryAll";

            // 1️⃣ 构建签名字符串（注意签名规则与 POST 相同）
            StringBuilder signingStrBuilder = new StringBuilder();
            signingStrBuilder.append("instruction=").append(instruction);
            signingStrBuilder.append("&marketType=").append(marketType);
            signingStrBuilder.append("&symbol=").append(symbol);
            signingStrBuilder.append("&timestamp=").append(ts);
            signingStrBuilder.append("&window=").append(window);

            String signingStr = signingStrBuilder.toString();
            String signature = sign(signingStr, INSTANCE.secretKey);
            // 3️⃣ 构建 GET 请求 URL
            String url = API_BASE + "/orders?marketType=" + URLEncoder.encode(marketType, "UTF-8")
                    + "&symbol=" + URLEncoder.encode(symbol, "UTF-8");

            // 4️⃣ 构建请求头
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("X-API-KEY",  INSTANCE.apiKey)
                    .addHeader("X-SIGNATURE", signature)
                    .addHeader("X-TIMESTAMP", String.valueOf(ts))
                    .addHeader("X-WINDOW", window)
                    .build();

            // 5️⃣ 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                int code = response.code();
                String respBody = response.body() != null ? response.body().string() : "<empty body>";

                if (!response.isSuccessful()) {
                    throw new RuntimeException("GET Open Orders failed: " + code + " -> " + respBody);
                }
                return respBody;
            }
        });


    }


    public static String getCurrentPosition(String symbol) throws Exception {
        return executeWithRetry(() ->{
            long ts = System.currentTimeMillis();
            String window = "5000";
            String instruction = "positionQuery";

            // 1️⃣ 构建签名字符串（注意签名规则与 POST 相同）
            StringBuilder signingStrBuilder = new StringBuilder();
            signingStrBuilder.append("instruction=").append(instruction);
            signingStrBuilder.append("&symbol=").append(symbol);
            signingStrBuilder.append("&timestamp=").append(ts);
            signingStrBuilder.append("&window=").append(window);
            String signingStr = signingStrBuilder.toString();
            String signature = sign(signingStr, INSTANCE.secretKey);

            // 3️⃣ 构建 GET 请求 URL
            String url = API_BASE + "/position?"
                    + "symbol=" + URLEncoder.encode(symbol, "UTF-8");
            // 4️⃣ 构建请求头
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("X-API-KEY",  INSTANCE.apiKey)
                    .addHeader("X-SIGNATURE", signature)
                    .addHeader("X-TIMESTAMP", String.valueOf(ts))
                    .addHeader("X-WINDOW", window)
                    .build();

            // 5️⃣ 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                int code = response.code();
                String respBody = response.body() != null ? response.body().string() : "<empty body>";
                if(Objects.equals(404,code)){
                    return "";
                }
                if (!response.isSuccessful()) {
                    throw new RuntimeException("GET Open Orders failed: " + code + " -> " + respBody);
                }
                return respBody;
            }
        });



    }

    /**
     * 使用 Ed25519 签名生成 Backpack API 所需签名
     *
     * @param signingStr 签名字符串（例如 instruction=orderCancel&symbol=...）
     * @param base64PrivateKey Base64 编码的原始私钥（来自 Backpack API）
     * @return Base64 编码的签名字符串
     */
    public static String sign(String signingStr, String base64PrivateKey) {
        try {
            // 1️⃣ 解码 Base64 私钥
            byte[] rawKey = Base64.getDecoder().decode(base64PrivateKey);

            // 2️⃣ 构造私钥参数
            Ed25519PrivateKeyParameters privKey = new Ed25519PrivateKeyParameters(rawKey, 0);

            // 3️⃣ 初始化签名器
            Ed25519Signer signer = new Ed25519Signer();
            signer.init(true, privKey);

            // 4️⃣ 输入待签名内容
            byte[] signingBytes = signingStr.getBytes(StandardCharsets.UTF_8);
            signer.update(signingBytes, 0, signingBytes.length);

            // 5️⃣ 生成签名
            byte[] sigBytes = signer.generateSignature();

            // 6️⃣ Base64 输出
            return Base64.getEncoder().encodeToString(sigBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to sign string: " + e.getMessage(), e);
        }
    }
    /**
     * 创建 TLS OkHttpClient
     */
    private OkHttpClient createTLSClient(boolean useProxy) {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public void checkClientTrusted(X509Certificate[] xcs, String s) {}
                        public void checkServerTrusted(X509Certificate[] xcs, String s) {}
                        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
                    }
            };

            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(System.out::println);
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);

            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(logging)
                    .retryOnConnectionFailure(true);

            if (useProxy) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 22307));
                builder.proxy(proxy);
            }

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Data
    public static class CancelOrderRequest {

        // 至少指定一个
        private Long clientId;   // uint32
        private String orderId;

        @NotNull
        private String symbol;   // 必填
    }

    public static String cancelOrder(CancelOrderRequest cancelOrderRequest) throws Exception {
        return executeWithRetry(() ->{
            try {
                long timestamp = System.currentTimeMillis();
                String window = "5000";
                String instruction = "orderCancel";

                // ✅ 使用和 POST/GET 一样的签名方法，body 顺序和签名一致
                String jsonBody = String.format(
                        "{\"orderId\":\"%s\",\"symbol\":\"%s\"}",
                        cancelOrderRequest.getOrderId(),
                        cancelOrderRequest.getSymbol()
                );

                // 构建签名字符串（和 jsonBody 一致）
                String signingStr = String.format("instruction=%s&orderId=%s&symbol=%s&timestamp=%d&window=%s",
                        instruction, cancelOrderRequest.getOrderId(), cancelOrderRequest.getSymbol(), timestamp, window
                );

                String signature = sign(signingStr,  INSTANCE.secretKey);

                RequestBody body = RequestBody.create(
                        jsonBody, MediaType.get("application/json; charset=utf-8")
                );

                Request request = new Request.Builder()
                        .url(API_BASE + "/order") // DELETE URL
                        .delete(body)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("X-API-KEY",  INSTANCE.apiKey)
                        .addHeader("X-SIGNATURE", signature)
                        .addHeader("X-TIMESTAMP", String.valueOf(timestamp))
                        .addHeader("X-WINDOW", window)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String respBody = response.body() != null ? response.body().string() : "<empty body>";

                    if (!response.isSuccessful()) {
                        throw new RuntimeException("HTTP DELETE failed: " + response.code() + " -> " + respBody);
                    }
                    return respBody;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });



    }




    /**
     * 获取账户资金信息（含权益、可用余额、未实现盈亏）
     * 对应 Backpack API: GET /api/v1/account
     */
    public static Map<String, WalletBalance> getAccountFunds() throws Exception {

        return executeWithRetry(() ->{
            long ts = System.currentTimeMillis();
            String window = "5000";
            String instruction = "balanceQuery";

            // 1️⃣ 构建签名字符串
            StringBuilder signingStrBuilder = new StringBuilder();
            signingStrBuilder.append("instruction=").append(instruction);
            signingStrBuilder.append("&timestamp=").append(ts);
            signingStrBuilder.append("&window=").append(window);
            String signingStr = signingStrBuilder.toString();

            // 2️⃣ 生成签名
            String signature = sign(signingStr,  INSTANCE.secretKey);

            // 3️⃣ 构建请求
            String url = API_BASE + "/capital";
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("User-Agent", "Mozilla/5.0 (Java OkHttpClient)")
                    .addHeader("Accept", "application/json")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("X-API-KEY",  INSTANCE.apiKey)
                    .addHeader("X-SIGNATURE", signature)
                    .addHeader("X-TIMESTAMP", String.valueOf(ts))
                    .addHeader("X-WINDOW", window)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                int code = response.code();
                String respBody = response.body() != null ? response.body().string() : "<empty body>";

                if (!response.isSuccessful()) {
                    throw new RuntimeException("GET Account Funds failed: " + code + " -> " + respBody);
                }

                Map<String, WalletBalance> balances = mapper.readValue(
                        respBody, new TypeReference<Map<String, WalletBalance>>() {}
                );
                return balances;
            }
        });



    }

    @Data
    public static class WalletBalance {
        private BigDecimal available = BigDecimal.ZERO;;
        private BigDecimal locked = BigDecimal.ZERO;
        private BigDecimal staked = BigDecimal.ZERO;
    }
    /**
     * 通用重试执行工具
     * @param task 需要执行的逻辑（lambda）
     * @param <T> 返回类型
     * @return 执行成功的结果
     */
    private static <T> T executeWithRetry(Callable<T> task) throws Exception {
        final int maxRetries = 3;          // 最大重试次数
        final long retryDelayMs = 2000;    // 每次重试间隔（毫秒）

        Exception lastException = null;

        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                return task.call();
            } catch (Exception e) {
                lastException = e;
                System.err.println("❌ 第 " + attempt + " 次调用失败：" + e.getMessage());
                if (attempt < maxRetries) {
                    System.out.println("⏳ 等待 " + retryDelayMs + "ms 后重试...");
                    Thread.sleep(retryDelayMs);
                }
            }
        }

        throw new RuntimeException("多次重试后仍失败", lastException);
    }



    // -------------------- 测试用 main --------------------
    public static void main(String[] args) throws Exception {
        BackpackApiClientRequest instance = BackpackApiClientRequest.getInstance("/t6YQSuvitAnUQFs8U9e2EzGSacF+zuk62xax0f0sFs=", "PNkR35Tdr24gNAUt6+x6MsiBsltQqdx58a4wv+nzQqw=");
        String result = instance.orderHistoryQueryAll();
        List<OrderInfo> orderInfos =mapper.readValue(result, new TypeReference<List<OrderInfo>>() {});
        orderInfos.stream().filter(k -> k.getId().equals("20183963144")).sorted(Comparator.comparing(OrderInfo::getCreatedAt).reversed()).collect(Collectors.toList());
        List<Map<String, Object>> bodyList = new ArrayList<>();
        Map<String, WalletBalance> accountFunds = new BackpackApiClientRequest(true).getAccountFunds();
        Map<String, Object> order = new HashMap<>();
        order.put("orderType", "Limit");            // 限价单
        order.put("symbol", "ASTER_USDC_PERP");     // 交易对
        order.put("side", "Ask");                   // 买入（卖出用 "Ask"）
        order.put("price", "1.300");                // 挂单价格
        order.put("quantity", "5");                 // 挂单数量
        order.put("timeInForce", "GTC");            // 挂单策略
        order.put("selfTradePrevention", "RejectTaker"); // 默认
        // market 或 limit
        bodyList.add(order);
        String post = new BackpackApiClientRequest(true).post(bodyList);
        //List<BackpackTradingBot.OrderResult> orders = mapper.readValue(post, new TypeReference<List<BackpackTradingBot.OrderResult>>() {});
        //System.out.println(orders);
        // 获取所有未完成订单
        String marketType = "PERP";     // 可选：SPOT、PERP 等
        String symbol = "ASTER_USDC_PERP"; // 可选：某个市场
       /* String currentPosition = new BackpackApiClientRequest(true).getCurrentPosition(symbol);
        List<BackpackTradingBot.BackpackPosition> positions = mapper.readValue(currentPosition, new TypeReference<List<BackpackTradingBot.BackpackPosition>>() {});*/
        getCurrentPosition(symbol);
        java.util.List<BackpackTradingBot.OrderResult> openOrders = mapper.readValue(new BackpackApiClientRequest(true).getOpenOrders(marketType, symbol), new TypeReference<List<BackpackTradingBot.OrderResult>>() {});
        System.out.println(openOrders);

        openOrders.forEach(k->{
            CancelOrderRequest order1 = new CancelOrderRequest();
            order1.setSymbol("ASTER_USDC_PERP");
            order1.setOrderId(k.getId());
            BackpackApiClientRequest backpackApiClientRequest = new BackpackApiClientRequest(true);
            try {
                String s = backpackApiClientRequest.cancelOrder(order1);
                System.out.println(s);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });

    }
}
